#include <stdio.h>
#include <openssl/ec.h>
#include <openssl/pem.h>

int generate_sm2_keypair(const char *priv_file, const char *pub_file) {
    EC_KEY *eckey = EC_KEY_new_by_curve_name(NID_sm2);
    if (!eckey) return -1;

    if (!EC_KEY_generate_key(eckey)) {
        EC_KEY_free(eckey);
        return -1;
    }

    FILE *fp = fopen(priv_file, "w");
    PEM_write_ECPrivateKey(fp, eckey, NULL, NULL, 0, NULL, NULL);
    fclose(fp);

    fp = fopen(pub_file, "w");
    PEM_write_EC_PUBKEY(fp, eckey);
    fclose(fp);

    EC_KEY_free(eckey);
    return 0;
}

int main() {
    if (generate_sm2_keypair("sm2private_key.pem", "sm2public_key.pem") == 0) {
        printf("SM2 key pair generated: sm2private_key.pem, sm2public_key.pem\n");
    } else {
        fprintf(stderr, "Failed to generate SM2 key pair\n");
        return 1;
    }
    return 0;
}
